[[...path]].page.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. import React, { useEffect } from 'react';
  2. import { pagePathUtils } from '@growi/core';
  3. import { isValidObjectId } from 'mongoose';
  4. import {
  5. NextPage, GetServerSideProps, GetServerSidePropsContext,
  6. } from 'next';
  7. import Head from 'next/head';
  8. import { useRouter } from 'next/router';
  9. // import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  10. // import { PageComments } from '~/components/PageComment/PageComments';
  11. // import { useTranslation } from '~/i18n';
  12. import { CrowiRequest } from '~/interfaces/crowi-request';
  13. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  14. // import { useIndentSize } from '~/stores/editor';
  15. // import { useRendererSettings } from '~/stores/renderer';
  16. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  17. import { IPageWithMeta } from '~/interfaces/page';
  18. import { PageModel } from '~/server/models/page';
  19. import { serializeUserSecurely } from '~/server/models/serializers/user-serializer';
  20. import { useSWRxCurrentPage, useSWRxPageInfo } from '~/stores/page';
  21. import loggerFactory from '~/utils/logger';
  22. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  23. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  24. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  25. // import DisplaySwitcher from '../client/js/components/Page/DisplaySwitcher';
  26. import { BasicLayout } from '../components/BasicLayout';
  27. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  28. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  29. import {
  30. useCurrentUser, useCurrentPagePath,
  31. useOwnerOfCurrentPage,
  32. useIsForbidden, useIsNotFound, useIsTrashPage, useShared, useShareLinkId, useIsSharedUser, useIsAbleToDeleteCompletely,
  33. useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification,
  34. useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsMailerSetup,
  35. useAclEnabled, useHasSlackConfig, useDrawioUri, useHackmdUri, useMathJax, useNoCdn, useEditorConfig, useCsrfToken,
  36. } from '../stores/context';
  37. import { CommonProps, getServerSideCommonProps, useCustomTitle } from './commons';
  38. // import { useCurrentPageSWR } from '../stores/page';
  39. const logger = loggerFactory('growi:pages:all');
  40. const { isUsersHomePage, isTrashPage: _isTrashPage } = pagePathUtils;
  41. type Props = CommonProps & {
  42. currentUser: string,
  43. pageWithMetaStr: string,
  44. // pageUser?: any,
  45. // redirectTo?: string;
  46. // redirectFrom?: string;
  47. // shareLinkId?: string;
  48. isForbidden: boolean,
  49. isNotFound: boolean,
  50. // isAbleToDeleteCompletely: boolean,
  51. isSearchServiceConfigured: boolean,
  52. isSearchServiceReachable: boolean,
  53. // isMailerSetup: boolean,
  54. // isAclEnabled: boolean,
  55. // hasSlackConfig: boolean,
  56. // drawioUri: string,
  57. // hackmdUri: string,
  58. // mathJax: string,
  59. // noCdn: string,
  60. // highlightJsStyle: string,
  61. // isAllReplyShown: boolean,
  62. // isContainerFluid: boolean,
  63. // editorConfig: any,
  64. // isEnabledStaleNotification: boolean,
  65. // isEnabledLinebreaks: boolean,
  66. // isEnabledLinebreaksInComments: boolean,
  67. // adminPreferredIndentSize: number,
  68. // isIndentSizeForced: boolean,
  69. };
  70. const GrowiPage: NextPage<Props> = (props: Props) => {
  71. // const { t } = useTranslation();
  72. const router = useRouter();
  73. const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
  74. // commons
  75. useAppTitle(props.appTitle);
  76. useSiteUrl(props.siteUrl);
  77. // useEditorConfig(props.editorConfig);
  78. useConfidential(props.confidential);
  79. useCsrfToken(props.csrfToken);
  80. // page
  81. useCurrentPagePath(props.currentPathname);
  82. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  83. // useIsForbidden(props.isForbidden);
  84. // useNotFound(props.isNotFound);
  85. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  86. // useShared(isSharedPage(props.currentPagePath));
  87. // useShareLinkId(props.shareLinkId);
  88. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  89. // useIsSharedUser(props.currentUser == null && isSharedPage(props.currentPagePath));
  90. // useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  91. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  92. useIsSearchServiceReachable(props.isSearchServiceReachable);
  93. // useIsMailerSetup(props.isMailerSetup);
  94. // useAclEnabled(props.isAclEnabled);
  95. // useHasSlackConfig(props.hasSlackConfig);
  96. // useDrawioUri(props.drawioUri);
  97. // useHackmdUri(props.hackmdUri);
  98. // useMathJax(props.mathJax);
  99. // useNoCdn(props.noCdn);
  100. // useIndentSize(props.adminPreferredIndentSize);
  101. // useRendererSettings({
  102. // isEnabledLinebreaks: props.isEnabledLinebreaks,
  103. // isEnabledLinebreaksInComments: props.isEnabledLinebreaksInComments,
  104. // adminPreferredIndentSize: props.adminPreferredIndentSize,
  105. // isIndentSizeForced: props.isIndentSizeForced,
  106. // });
  107. // const { data: editorMode } = useEditorMode();
  108. let pageWithMeta: IPageWithMeta | undefined;
  109. if (props.pageWithMetaStr != null) {
  110. pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageWithMeta;
  111. }
  112. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  113. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  114. const classNames: string[] = [];
  115. // switch (editorMode) {
  116. // case EditorMode.Editor:
  117. // classNames.push('on-edit', 'builtin-editor');
  118. // break;
  119. // case EditorMode.HackMD:
  120. // classNames.push('on-edit', 'hackmd');
  121. // break;
  122. // }
  123. // if (props.isContainerFluid) {
  124. // classNames.push('growi-layout-fluid');
  125. // }
  126. // if (page == null) {
  127. // classNames.push('not-found-page');
  128. // }
  129. // // Rewrite browser url by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  130. // useEffect(() => {
  131. // if (props.redirectTo != null) {
  132. // router.push('/[[...path]]', props.redirectTo, { shallow: true });
  133. // }
  134. // // eslint-disable-next-line react-hooks/exhaustive-deps
  135. // }, []);
  136. const alertForNextRouter = () => {
  137. window.alert('alert!!!');
  138. return;
  139. };
  140. const alertForJs = (e) => {
  141. e.preventDefault();
  142. window.alert('alert!!!');
  143. e.returnValue = '';
  144. return;
  145. };
  146. /*
  147. * Route changes by Browser
  148. * Example: window.location.href, F5
  149. */
  150. useEffect(() => {
  151. window.addEventListener('beforeunload', alertForJs);
  152. return () => {
  153. window.removeEventListener('beforeunload', alertForJs);
  154. };
  155. }, []);
  156. /*
  157. * Route changes by Next Router
  158. * https://nextjs.org/docs/api-reference/next/router
  159. */
  160. useEffect(() => {
  161. router.events.on('routeChangeStart', alertForNextRouter)
  162. return () => {
  163. router.events.off('routeChangeStart', alertForNextRouter)
  164. };
  165. }, []);
  166. return (
  167. <>
  168. <Head>
  169. {/*
  170. {renderScriptTagByName('drawio-viewer')}
  171. {renderScriptTagByName('mathjax')}
  172. {renderScriptTagByName('highlight-addons')}
  173. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  174. */}
  175. </Head>
  176. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  177. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  178. <header className="py-0">
  179. {/* <GrowiSubNavigation /> */}
  180. GrowiSubNavigation
  181. </header>
  182. <div className="d-edit-none">
  183. {/* <GrowiSubNavigationSwitcher /> */}
  184. GrowiSubNavigationSwitcher
  185. </div>
  186. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  187. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  188. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  189. <div className="row">
  190. <div className="col grw-page-content-container">
  191. <div id="content-main" className="content-main grw-container-convertible">
  192. {/* <PageAlerts /> */}
  193. PageAlerts<br />
  194. {/* <DisplaySwitcher /> */}
  195. DisplaySwitcher<br />
  196. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  197. {/* <PageStatusAlert /> */}
  198. PageStatusAlert
  199. </div>
  200. </div>
  201. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  202. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  203. <div id="revision-toc-content" className="revision-toc-content"></div>
  204. </div>
  205. </div> */}
  206. </div>
  207. </div>
  208. <footer>
  209. {/* <PageComments /> */}
  210. PageComments
  211. </footer>
  212. </BasicLayout>
  213. </>
  214. );
  215. };
  216. async function injectPageInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  217. const req: CrowiRequest = context.req as CrowiRequest;
  218. const { crowi } = req;
  219. const Page = crowi.model('Page');
  220. const { pageService } = crowi;
  221. const { user } = req;
  222. const { currentPathname } = props;
  223. // determine pageId
  224. let pageId;
  225. const pageIdStr = currentPathname.substring(1);
  226. pageId = isValidObjectId(pageIdStr) ? pageIdStr : null;
  227. const result: IPageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  228. const page = result.data;
  229. if (page == null) {
  230. const count = pageId != null ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  231. // check the page is forbidden or just does not exist.
  232. props.isForbidden = count > 0;
  233. props.isNotFound = true;
  234. logger.warn(`Page is ${props.isForbidden ? 'forbidden' : 'not found'}`, currentPathname);
  235. }
  236. await (page as unknown as PageModel).populateDataToShowRevision();
  237. props.pageWithMetaStr = JSON.stringify(result);
  238. }
  239. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  240. // const req: CrowiRequest = context.req as CrowiRequest;
  241. // const { crowi } = req;
  242. // const UserModel = crowi.model('User');
  243. // if (isUserPage(props.currentPagePath)) {
  244. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  245. // if (user != null) {
  246. // props.pageUser = JSON.stringify(user.toObject());
  247. // }
  248. // }
  249. // }
  250. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  251. const req: CrowiRequest = context.req as CrowiRequest;
  252. const { crowi } = req;
  253. const {
  254. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  255. } = crowi;
  256. const { user } = req;
  257. const result = await getServerSideCommonProps(context);
  258. // check for presence
  259. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  260. if (!('props' in result)) {
  261. throw new Error('invalid getSSP result');
  262. }
  263. const props: Props = result.props as Props;
  264. await injectPageInformation(context, props);
  265. if (user != null) {
  266. props.currentUser = JSON.stringify(user);
  267. }
  268. props.isSearchServiceConfigured = searchService.isConfigured;
  269. props.isSearchServiceReachable = searchService.isReachable;
  270. // props.isMailerSetup = mailService.isMailerSetup;
  271. // props.isAclEnabled = aclService.isAclEnabled();
  272. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  273. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  274. // props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  275. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  276. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  277. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  278. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  279. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  280. // props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  281. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  282. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  283. // props.editorConfig = {
  284. // upload: {
  285. // image: crowi.fileUploadService.getIsUploadable(),
  286. // file: crowi.fileUploadService.getFileUploadEnabled(),
  287. // },
  288. // };
  289. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  290. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  291. return {
  292. props,
  293. };
  294. };
  295. export default GrowiPage;